package com.example.flutter_demo2

import android.app.Application
import androidx.core.splashscreen.SplashScreen
import com.example.flutter_demo2.aty.OnSwitch2Web
import com.example.flutter_demo2.contants.Pages
import com.example.flutter_demo2.plugins.common.CommonPlugin
import com.example.flutter_demo2.plugins.router.FlutterRouterObserver
import com.example.flutter_demo2.plugins.router.RouterPlugin
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.dart.DartExecutor


class MyApplication : Application() {

    companion object {
        const val fragmentEngineName = "fragmentEngine"
//        const val secondEngineName = "secondEngine"
//        const val singleEngineName = "singleEngine"

        lateinit var splashScreen: SplashScreen

        fun registerEngine(flutterEngine: FlutterEngine) {
            // 插件注册
//            GeneratedPluginRegistrant.registerWith(flutterEngine)
            flutterEngine.plugins.add(CommonPlugin())
            flutterEngine.plugins.add(RouterPlugin())
            // platform view 注册
            // flutterEngine.platformViewsController.registry.registerViewFactory("TestView", AndroidPlatformViewFactory(flutterEngine))
        }
    }

    // multi engine
//    private lateinit var secondEngine: FlutterEngine

    // fragment engine
    private lateinit var fragmentEngine: FlutterEngine

    // single engine
//    private lateinit var singleEngine: FlutterEngine

    override fun onCreate() {
        super.onCreate()
        initEngines()
    }

    private fun initEngines() {
        // 预热缓存引擎：引擎1：fragment用，引擎2，从原生，新开的flutter页面
        // Instantiate a FlutterEngine.
        fragmentEngine = FlutterEngine(this)
        // Configure an initial route.
        fragmentEngine.navigationChannel.setInitialRoute(Pages.appEntryPage)
        // Start executing Dart code to pre-warm the FlutterEngine.
        // after attach root activity
        fragmentEngine.dartExecutor.executeDartEntrypoint(
            DartExecutor.DartEntrypoint.createDefault()
        )
        // register engine
        registerEngine(fragmentEngine)
        // Cache the FlutterEngine to be used by FlutterActivity or FlutterFragment.
        FlutterRouterObserver.initChannel(fragmentEngine) {
            when (it) {
                1 -> {
                    println("finish")
                }
            }
        }
        FlutterEngineCache
            .getInstance()
            .put(fragmentEngineName, fragmentEngine)

//        singleEngineName = FlutterEngine(this)
//        singleEngineName.navigationChannel.setInitialRoute(Pages.appEntryPage)
//        singleEngineName.dartExecutor.executeDartEntrypoint(
//            DartExecutor.DartEntrypoint.createDefault()
//        )
//        registerEngine(singleEngineName)
//        FlutterEngineCache
//            .getInstance()
//            .put(singleEngineName, singleEngineName)
    }
}
